<template>
  <ContentWrap>
    <el-row style="height: calc(100vh - 150px)">
      <el-col :span="10">
        <el-form
          ref="formRef"
          :inline="true"
          v-loading="formLoading"
          :model="formData"
          :rules="formCopyright"
          label-width="100px"
        >
          <el-form-item label="区域名称:" prop="name">
            <el-input
              v-model="formData.name"
              class="!w-240px"
              :disabled="disabled"
              clearable
              placeholder="请输入区域名称"
            />
          </el-form-item>
          <el-form-item label="区域范围:" prop="type" style="position: relative">
            <el-radio-group v-model="formData.type" class="!w-300px" :disabled="disabled">
              <el-radio :value="0" @click="clickClose">上传空间区域文件</el-radio>
              <el-radio :value="1" @click="clickRadio">按行政区划选择</el-radio>
            </el-radio-group>
            <ProvinceCity
              ref="provinceRef"
              :regionLists="formData.regionList"
              @querySelect="querySelect"
            ></ProvinceCity>
          </el-form-item>

          <el-form-item label=" " prop="fileId" v-if="formData.type == 0" style="width: 100%">
            <UploadFile
              v-model="formData.list"
              @uploadSuccess="uploadSuccess"
              :disabled="disabled"
              :limit="1"
            ></UploadFile>
          </el-form-item>

          <el-form-item label=" " v-if="formData.type == '1'">
            {{ regionLists }}
          </el-form-item>
        </el-form>
        <el-button :disabled="formLoading" type="primary" @click="submitForm" v-if="!disabled"
          >保 存</el-button
        >
        <el-button @click="setClose()">取 消</el-button>
        <div style="height: 300px"></div>
      </el-col>
      <el-col :span="12" style="padding: 10px">
        <LoadMap :fileidInfo="fileidInfo" style="height: 100%" />
      </el-col>
    </el-row>
  </ContentWrap>
</template>

<script lang="ts" setup>
import * as populationDensityApi from '@/api/responseLevel/populationDensity'
import LoadMap from '@/views/earthquake/earthquakeServer/gis/LoadMap.vue'
import UploadFile from './UploadFile.vue'
import ProvinceCity from './provinceCity.vue'
defineOptions({ name: 'populationDensityForm' })
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
// const TmapDivRef = ref()

const provinceRef = ref()
const formRef = ref() // 表单 Ref
const formData = ref<any>({
  id: undefined,
  name: '',
  type: undefined,
  list: [],
  fileIds: '',
  regionList: []
})
const regionLists = ref('')
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formCopyright = reactive({
  name: [{ required: true, message: '区域名称不能为空', trigger: 'blur' }],
  type: [{ required: true, message: '区域范围不能为空', trigger: 'change' }]
})
const updateUrl = ref(import.meta.env.VITE_BASE_URL + '/admin-api/attachment/uploadFile')
const disabled = ref(false) //查看禁用

const fileidInfo = ref({
  fileid: '',
  type: 0,
  xzqh:[],
  query: {
    tableName: '',
    fields: '',
    // owner:"private"
    
  }
})

//初始化 type 0 -- 临时表 1 ---正式表 owner public公库 private四库
// const fileidInfo = ref({
//   fileid: route.query.type == 'create' ?'' :'eqim_'+route.query.id,
//   type:route.query.type == 'create' ? 0 :1,
//   query:{
//     tableName:route.query.type == 'create' ? 'temp_shp_data' :'earthquake_shp',
//     fields: route.query.type == 'create' ?'id': 'id,p_id,province,city',
//     owner:"public"
//   }
// });

// 上传成功
const uploadSuccess = (value) => {
  formData.value.list = value;
  
  console.log(value);
  
   fileidInfo.value.type = 0
    fileidInfo.value.query.tableName = 'temp_file_data'
    fileidInfo.value.query.fields = 'id'
  fileidInfo.value.fileid = value[0].id
}
const open = async (type: string, id) => {
  if (type == 'detail' || type == 'update') {
    
    fileidInfo.value.type = 1
    fileidInfo.value.fileid = id
    fileidInfo.value.query.tableName = 'res_level_region_sub'
    fileidInfo.value.query.fields = 'id,p_id,province,city'
  } else {
    fileidInfo.value.type = 0
    fileidInfo.value.fileid = ''
    fileidInfo.value.query.tableName = 'temp_file_data'
    fileidInfo.value.query.fields = 'id'
  }

  resetForm()
  disabled.value = type == 'detail'
  formType.value = type
  // 修改时，设置数据
  if (id) {
    try {
      formData.value = await populationDensityApi.getPopulationDensityDetail(id)
      if (formData.value.type == 0) {
        formData.value.list.forEach((item) => {
          item.name = item.attachName
          item.url = item.attachPath
        })
      }
      if (formData.value.regionList && formData.value.regionList.length > 0) {
        let data: any = []
        formData.value.regionList.forEach((item) => {
          if (item.city) {
            data.push(item.province + '-' + item.city)
          } else {
            data.push(item.province)
          }
        })
        regionLists.value = data.join(',')
      } else {
        formData.value.regionList = []
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗
/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    name: '',
    type: undefined,
    list: [],
    fileIds: '',
    regionList: []
  }
  formRef.value?.resetFields()
}

/** 提交表单 */
const emit = defineEmits(['success', 'setClose']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  if (formData.value.type == 0) {
    if (formData.value.list.length == 0) {
      message.warning('请上传shp数据')
      return
    }
    formData.value.fileIds = formData.value.list.map((item) => item.url).join(',')
  } else {
    if (formData.value.regionList.length == 0) {
      message.warning('请选择行政区划')
      return
    }
  }
  // 提交请求
  formLoading.value = true
  try {
    if (formType.value == 'update') {
      await populationDensityApi.createCopyright({ ...formData.value })
      message.success(t('common.updateSuccess'))
    } else {
      await populationDensityApi.createCopyright({ ...formData.value })
      message.success(t('common.createSuccess'))
    }
    // 发送操作成功的事件
    emit('success')
    setClose()
  } finally {
    formLoading.value = false
  }
}
const setClose = () => {
  emit('setClose')
}
const clickRadio = () => {
  if (disabled.value) return
  provinceRef.value.open()
}
const clickClose = () => {
  if (disabled.value) return
  provinceRef.value?.close()
}
const querySelect = (value) => {
  //  fileidInfo.value.type = 1;
  //  fileidInfo.value.fileid = '1';
var cityArr: any = [];

  let data: any = []
  value.forEach((item) => {
    if (item.city) {
      data.push(item.province + '-' + item.city);
      cityArr.push({
        code:item.code,
        name:item.city,
        type:3
      });
    } else {
      data.push(item.province)
      if(item.province == "全国"){
         cityArr.push({
        code:"",
        name:item.province,
        type:1
      });
      return
      }
      if(item.code){
      cityArr.push({
              code:item.code,
              name:item.province,
              type:2
            });
      }
       
    }
  })
  regionLists.value = data.join(',')
  formData.value.regionList = value
  // const fileStr = cityArr.join(',');
  console.log(cityArr);
    fileidInfo.value.type = 2;
     fileidInfo.value.fileid = Date.now() +"";
    fileidInfo.value.xzqh = cityArr;
}
</script>

<style lang="scss" scoped>
</style>
